<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="goods_price"
          width="95px"
        ></el-table-column>
        <el-table-column
          label="商品重量"
          prop="goods_weight"
          width="70px"
        ></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="140px">
          <template v-slot="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.goods_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 修改的对话框 -->
    <el-dialog title="修改商品(未完善)" :visible.sync="editDialogVisible" width="50%">
      <!-- 添加参数的表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="110px"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="editForm.goods_introduce"> </quill-editor>
        </el-form-item>
        <el-form-item label="上传图片的路径" prop="pics">
          <el-input
            v-for="(item, index) in editForm.pics"
            :key="index"
            v-model="item.pics_big_url"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="上传的图片">
          <div>
            <img
              :src="item.pics_big_url"
              alt=""
              style="width: 30%; margin: 10px"
              v-for="(item, index) in editForm.pics"
              :key="index"
            />
          </div>
          <el-upload
            :action="uploadURL"
            :headers="headerObj"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品参数(只读)">
          <div v-for="(item, index) in editForm.attrs" :key="index">
            {{ item.attr_name + ':'}}
            <el-tag>{{ item.attr_vals }}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <!-- 页脚按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表
      goodslist: [],
      // 总条数
      total: 0,
      // 编辑的弹框显示与隐藏
      editDialogVisible: false,
      // 编辑弹框的双向绑定数据
      editForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: ''
      },
      // 编辑弹框内的效验规则
      editFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      // 上传图片的 url 地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径
      previewPath: ''
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败！')
      }

      console.log(res.data)
      this.goodslist = res.data.goods
      this.total = res.data.total
    },
    // 监听每页变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 监听每页数量变化
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 删除商品
    async removeById(id) {
      // 弹框提示用户删除用户
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 如果用户确认删除返回值是字符串 confirm
      // 如果用户取消删除则返回值是字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`goods/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('取消失败')
      }
      this.$message.success('删除成功')
      this.getGoodsList()
    },
    // 到添加商品页面
    goAddpage() {
      this.$router.push('/goods/add')
    },
    // 打开编辑对话框
    async showEditDialog(id) {
      // console.log(id)
      // 查询当前商品的信息
      const { data: res } = await this.$http.get(`goods/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('获得参数名失败')
      }
      this.editForm = res.data
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 编辑商品数据
    editGoods() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.editForm)
        var cateId = this.editForm.goods_id
        const { data: res } = await this.$http.put(
          `goods/${cateId}`,
          {
            goods_name: this.editForm.goods_name,
            goods_price: this.editForm.goods_price,
            goods_number: this.editForm.goods_number,
            goods_weight: this.editForm.goods_weight,
            goods_introduce: this.editForm.goods_introduce,
            pics: this.editForm.pics,
            attrs: this.editForm.attrs,
            goods_cat: this.editForm.goods_cat
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }

        this.$message.success('修改参数成功！')
        this.getGoodsList()
        this.editDialogVisible = false
      })
    },
    // 处理移除图片的操作
    handleRemove(file) {
      console.log(file)
      // 1.获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从 pics 数组中，找到这个图片对应的索引值
      const i = this.editForm.pics.findIndex((x) => x.pic === filePath)
      // 3.调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.editForm.pics.splice(i, 1)
      console.log(this.editForm)
    },
    // 监听图片上传成功的事件
    handleSuccess(res) {
      // console.log(res)
      // 1.拼接得到一个图片信息对象
      const picInfo = { pic: res.data.tmp_path }
      // 2.将图片信息对象push到pics数组中
      this.editForm.pics.push(picInfo)
      console.log(this.editForm)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
